package cloud.misiro.spring.cloud.zuul.filters.pre;

import cloud.misiro.spring.cloud.zuul.filters.Route;
import cloud.misiro.spring.cloud.zuul.filters.RouteLocator;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static cloud.misiro.spring.cloud.zuul.filters.support.FilterConstants.*;

public class PreDecorationFilter extends ZuulFilter {

    private static final Logger logger = LoggerFactory.getLogger(PreDecorationFilter.class);

    private final RouteLocator routeLocator;

    public PreDecorationFilter(RouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 5;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        String requestURI = requestContext.getRequest().getRequestURI();
        Route route = routeLocator.getMatchingRoute(requestURI);
        if (route != null) {
            requestContext.put(REQUEST_URI_KEY, route.getPath());
            requestContext.set(SERVICE_ID_KEY, route.getLocation());
        } else {
            logger.error("获取不到匹配的路由, requestURI: {}", requestContext);
        }

        return null;
    }
}
